﻿using ContactSMS.Client.Models;
using ContactSMS.Client.Response;
using Newtonsoft.Json;
using System.Net.Http.Headers;

namespace ContactSMS.Client.Service
{
    public class MessageService : BaseService
    {
        HttpClient httpClient;

        public MessageService()
        {
            this.httpClient = new HttpClient();
        }

        public async Task<QResponse<PagedResponse<MessageSessionModelNew>>> GetMessageSessionsAsync(int page = 1, int pageSize = 1000)
        {
            var accessToken = await AuthService.GetAccessTokenAsync();
            if (string.IsNullOrEmpty(accessToken))
            {
                throw new InvalidOperationException("Access token is missing. Please log in again.");
            }
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            string url = $"{baseUrl}/api/MessageSession/GetMessageSessions?page={page}&pageSize={pageSize}";

            var response = await httpClient.GetAsync(url);
            response.EnsureSuccessStatusCode();
            var resultContent = await response.Content.ReadAsStringAsync();
            Console.WriteLine(resultContent);
            var registerResponse = JsonConvert.DeserializeObject<QResponse<PagedResponse<MessageSessionModelNew>>>(resultContent);
            return registerResponse;
        }

        public async Task<QResponse<PagedResponse<MessageNewModel>>> GetMessageAsync(long id, int page = 1, int pageSize = 15)
        {
            var accessToken = await AuthService.GetAccessTokenAsync();
            if (string.IsNullOrEmpty(accessToken))
            {
                throw new InvalidOperationException("Access token is missing. Please log in again.");
            }
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            string url = $"{baseUrl}/api/Message/GetMessage?MessageSessionId={id}&page={page}&pageSize={pageSize}";
            var response = await httpClient.GetAsync(url);
            response.EnsureSuccessStatusCode();
            var resultContent = await response.Content.ReadAsStringAsync();
            Console.WriteLine(resultContent);
            var registerResponse = JsonConvert.DeserializeObject<QResponse<PagedResponse<MessageNewModel>>>(resultContent);
            return registerResponse;
        }
    }
}
